/**
 * WebViewController.m
 *
 * The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License 
 * at http://www.mozilla.org/MPL/
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied. See the License for the specific language governing rights and limitations 
 * under the License.
 *
 * The Original Code is gcast-toolbox4iphone.
 *
 * The Initial Developers of the Original Code is Giannandrea Castaldi.
 */
#import "GTWebViewController.h"
#import "UIKit+GTExtensions.h"

#define BACKWARD_ARROW 0
#define EMPTY_SEGMENT 1
#define FORWARD_ARROW 2

@interface GTWebViewController ()
@property(nonatomic,retain) NSURLRequest *request;
@property(nonatomic,retain) NSString *html;
@property(nonatomic,assign) BOOL toolbarEnabled;
@property(nonatomic,retain) UISegmentedControl *navigationButtons;
@property(nonatomic,retain) UIActivityIndicatorView *activityWheel;

- (void)updateNavigationArrows;
@end

@implementation GTWebViewController
@synthesize request, html, toolbarEnabled, webView, navigationButtons, activityWheel, logRequests, webViewDelegate;

- (id)initWithRequest:(NSURLRequest*)aRequest toolbarEnabled:(BOOL)toolbarEnabledFlag {
  if ((self = [super init])) {
    self.request = aRequest;
    self.toolbarEnabled = toolbarEnabledFlag;
    self.logRequests = FALSE;
  }
  return self;
}

- (id)initWithHtml:(NSString*)htmlPage toolbarEnabled:(BOOL)toolbarEnabledFlag {
  if ((self = [super init])) {
    self.html = htmlPage;
    self.toolbarEnabled = toolbarEnabledFlag;
    self.logRequests = FALSE;
  }
  return self;
}

- (void)loadView {
  // Init webview
  self.webView = [[[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 460.0)] autorelease];
  self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  webView.scalesPageToFit = TRUE;
  webView.dataDetectorTypes = UIDataDetectorTypeLink;
  webView.delegate = self;
  self.view = webView;
  
  // Init activity view
  self.activityWheel = [[[UIActivityIndicatorView alloc] initFlexibleWithFrame:CGRectMake(0.0, 0.0, 25.0, 25.0)
                                                    activityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite] autorelease];  
  // Init navigation buttons
  if (self.toolbarEnabled) {
    self.navigationButtons = [[[UISegmentedControl alloc] initWithItems:
                               [NSArray arrayWithObjects:
                                [UIImage imageNamed:@"left-arrow.png"],
                                [UIImage imageNamed:@"empty.png"],
                                [UIImage imageNamed:@"right-arrow.png"],
                                nil]] autorelease];
    navigationButtons.frame = CGRectMake(0, 0, 90, 30.0);
    navigationButtons.segmentedControlStyle = UISegmentedControlStyleBar;
    navigationButtons.momentary = YES;
    [navigationButtons addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];  
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:navigationButtons] autorelease];
  }
  if (self.request) {
    [webView loadRequest:self.request];
  }
  if (self.html) {
    [webView loadHTMLString:self.html baseURL:nil];
  }
  [self updateNavigationArrows];
}

- (void)dealloc {
  [request release];
  [html release];
  [webView release];
  [navigationButtons release];
  [activityWheel release];
  [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  return TRUE;
}

- (IBAction)segmentAction:(id)sender {
	UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
  switch (segmentedControl.selectedSegmentIndex) {
    case BACKWARD_ARROW:
      [webView goBack];
      break;
    case FORWARD_ARROW:
      [webView goForward];
      break;
  }
}

#pragma mark delegate methods

- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)aRequest navigationType:(UIWebViewNavigationType)navigationType {
  if (self.logRequests) {
    NSLog(@"request                     : %@", aRequest);
    NSLog(@"request.HTTPMethod          : %@", [aRequest HTTPMethod]);
    NSLog(@"request.allHTTPHeaderFields : %@", [aRequest allHTTPHeaderFields]);
    NSLog(@"request.HTTPBody            : %@", [[[NSString alloc] initWithData:[aRequest HTTPBody] encoding:NSASCIIStringEncoding] autorelease]);
  }
  return (self.webViewDelegate ? [self.webViewDelegate webView:aWebView shouldStartLoadWithRequest:aRequest navigationType:navigationType] : TRUE);
}

- (void)webViewDidStartLoad:(UIWebView *)aWebView {
  self.navigationItem.titleView = activityWheel;  
  [activityWheel startAnimating];  
  [self updateNavigationArrows];
  if (self.webViewDelegate) {
    [self.webViewDelegate webViewDidStartLoad:aWebView];
  }
}

- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
  self.navigationItem.titleView = nil;
  [activityWheel stopAnimating];  
  [self updateNavigationArrows];
  if (self.webViewDelegate) {
    [self.webViewDelegate webViewDidFinishLoad:aWebView];
  }
}

- (void)webView:(UIWebView *)aWebView didFailLoadWithError:(NSError *)error {
  if (self.webViewDelegate) {
    [self.webViewDelegate webView:aWebView didFailLoadWithError:error];
  }
}

#pragma mark private methods

- (void)updateNavigationArrows {
  if (navigationButtons) {
    [navigationButtons setEnabled:webView.canGoBack forSegmentAtIndex:BACKWARD_ARROW];
    [navigationButtons setEnabled:FALSE forSegmentAtIndex:EMPTY_SEGMENT];  
    [navigationButtons setEnabled:webView.canGoForward forSegmentAtIndex:FORWARD_ARROW];
  }
}

- (void)didReceiveMemoryWarning {
  NSLog(@"%@: didReceiveMemoryWarning", self);
}

@end
